﻿using System;
using System.Linq;
using System.Web.Security;
using System.Web.UI.WebControls;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore.Pages.Account {

    public partial class Login : System.Web.UI.Page {

        protected void LoginButton_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            var userName = (this.PageLoginView.FindControl("UserNameTextBox") as TextBox).Text.ToLower();
            var password = (this.PageLoginView.FindControl("PasswordTextBox") as TextBox).Text;
            var persistentLogon = (this.PageLoginView.FindControl("RememberMeCheckBox") as CheckBox).Checked;

            // Check authentication
            if (!Membership.ValidateUser(userName, password)) {
                this.ModelState.AddModelError("AuthError", "Bylo zadáno chybné uživatelské jméno, heslo nebo je uživatel zablokován.");
                return;
            }

            using (var dc = new FluffyDbContext()) {
                var user = dc.Users.Single(x => x.UserName.Equals(userName));

                // Register last known IP address
                user.LastLoginIpAddress = this.Request.UserHostAddress;
                dc.SaveChanges();

                // Handle minor status
                var isCurrentlyMinor = Roles.IsUserInRole(userName, Role.MinorsRoleName);
                var shouldBeMinor = !user.Age.HasValue || user.Age < 18;
                if (isCurrentlyMinor && !shouldBeMinor) {
                    // Remove minors flag
                    Roles.RemoveUserFromRole(userName, Role.MinorsRoleName);
                }
                else if (!isCurrentlyMinor && shouldBeMinor) {
                    // Add minors flag
                    Roles.AddUserToRole(userName, Role.MinorsRoleName);
                }
            }

            // Sign in
            FormsAuthentication.RedirectFromLoginPage(userName, persistentLogon);
        }

        protected void Page_Load(object sender, EventArgs e) {
        }
    }
}